<?php

use App\Services\Obs\ObsClient;
use OSS\OssClient;

/**
 * oss上传文件
 */
if (!function_exists('oss_upload_file')) {
    function oss_upload_file($object, $file_path)
    {
        $accessKeyId = getenv('OSS_ACCESSKEYID'); ;
        $accessKeySecret = getenv('OSS_ACCESSKEYSECRET');
        $endpoint = getenv('OSS_ENDPOINT');
        $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
        $bucket = getenv('OSS_BUCKET');
        $upload_res = $ossClient->uploadFile($bucket, $object, $file_path);
        if (!empty($upload_res['info']) && $upload_res['info']['http_code'] == 200 && !empty($upload_res['info']['url'])) {
            return $upload_res['info']['url'];
        }
        return false;
    }
}

/**
 * obs初始化
 * @return ObsClient
 */
if (!function_exists('obs_client')) {
    function obs_client()
    {
        $ak = getenv('OBS_AK');
        $sk = getenv('OBS_SK');
        $endpoint = 'https://obs.cn-north-4.myhuaweicloud.com';
        return ObsClient::factory(array(
            'key' => $ak,
            'secret' => $sk,
            'endpoint' => $endpoint,
            'signature' => 'obs'
        ));
    }
}

/**
 * obs上传文件
 * @param $bucket_name
 * @param $object_key
 * @param $file_path
 * @return bool
 */
if (!function_exists('obs_upload_file')) {
    function obs_upload_file($object_key, $file_path)
    {
        $bucket_name = getenv('OBS_BUCKET');
        $obsClient = obs_client();
        $resp = $obsClient->putObject(array(
            'Bucket' => $bucket_name,
            'Key' => $object_key,
            'SourceFile' => $file_path
        ));
        if ($resp['HttpStatusCode'] != 200) {
            \Illuminate\Support\Facades\Log::error('obs上传失败', [
                'bucket_name' => $bucket_name,
                'object_key' => $object_key,
                'file_path' => $file_path,
                'resp' => $resp
            ]);
            return false;
        }
        return true;
    }
}

/**
 * obs获取分享链接
 * @param $bucket_name
 * @param $object_key
 * @param $file_path
 * @return false|mixed|null
 */
if (!function_exists('obs_get_url')) {
    function obs_get_url($bucket_name, $object_key, $file_path)
    {
        $obsClient = obs_client();
        $res_url = $obsClient->createSignedUrl(array(
            'Method' => 'GET',
            'Bucket' => $bucket_name,
            'Key' => $object_key,
            'SourceFile' => $file_path,
            'Expires' => 60 * 60 * 24
        ));
        if (empty($res_url['SignedUrl'])) {
            \Illuminate\Support\Facades\Log::error('obs获取链接失败', [
                'bucket_name' => $bucket_name,
                'object_key' => $object_key,
                'file_path' => $file_path,
                'res_url' => $res_url
            ]);
            return false;
        }
        return $res_url['SignedUrl'];
    }
}

/**
 * obs获取目录下文件
 * @param $bucket_name
 * @param $object_key
 * @return array
 */
if (!function_exists('obs_get_object_list')) {
    function obs_get_object_list($bucket_name, $object_key)
    {
        $obsClient = obs_client();
        $obs_res = $obsClient->listObjects([
            'Bucket' => $bucket_name,
            'Marker' => $object_key
        ]);
        return $obs_res['Contents'] ?? [];
    }
}

/**
 * 二维数组按照指定字段分组并排序
 */
if (!function_exists('array_group_sort')) {
    function array_group_sort($array, $field, $order = 'desc')
    {
        usort($array, function ($a, $b) use ($field, $order) {
            if ($order === 'desc') {
                return strtotime($b[$field]) - strtotime($a[$field]);
            } else {
                return strtotime($a[$field]) - strtotime($b[$field]);
            }
        });

        $groupedArray = [];
        foreach ($array as $item) {
            $value = $item[$field];
            if (!isset($groupedArray[$value])) {
                $groupedArray[$value] = [];
            }
            $groupedArray[$value][] = $item;
        }
        return $groupedArray;
    }
}

/**
 * 分页
 */
if (!function_exists('custom_paginate')) {
    function custom_paginate($page_list, $list)
    {
        return [
            'page' => $page_list->currentPage(),
            'prevt_page' => !($page_list->onFirstPage() == true),
            'next_page' => $page_list->hasMorePages(),
            'last_page' => $page_list->lastPage(),
            'limit' => $page_list->perPage(),
            'total' => $page_list->total(),
            'list' => $list,
        ];
    }
}

/**
 * 计算时间差
 */
if (!function_exists('time_diff')) {
    function time_diff($time1, $time2)
    {
        // 创建 DateTime 对象
        $time1 = new DateTime($time1);
        $time2 = new DateTime($time2);
        // 计算时间差
        $interval = $time1->diff($time2);
        // 将时间差转换为小时
        $hours = $interval->h + ($interval->i / 60) + ($interval->s / 3600);
        // 根据时间先后顺序确定正负
        if ($time1 > $time2) {
            $hours = -$hours;
        }
        // 输出结果，保留两位小数
        return round($hours, 2);
    }
}

/**
 * Excel日期转换
 */
if (!function_exists('excel_date_to_time')) {
    function excel_date_to_time($excelDate)
    {
        $baseDate = new DateTime('1899-12-30');
        // 获取天数部分
        $days = intval($excelDate);
        // 获取时间部分（小数部分）
        $timeFraction = $excelDate - $days;
        // 计算日期
        $date = clone $baseDate;
        $date->modify("+$days days");
        // 计算时间（秒数）
        $seconds = intval($timeFraction * 86400); // 86400秒 = 1天
        // 将秒数转换为时分秒
        $hours = intval($seconds / 3600);
        $minutes = intval(($seconds % 3600) / 60);
        $seconds = $seconds % 60;
        // 设置时间部分
        $date->setTime($hours, $minutes, $seconds);
        // 返回格式化后的日期时间
        return $date->format('Y-m-d H:i:s');
    }

}

/**
 * 文档转换-Excel转pdf
 */
if (!function_exists('doc_convert')) {
    function doc_convert($file_url, $table_name, $table_id, $table_col, $is_new = true)
    {
        if (!defined('CURL_SSLVERSION_TLSv1_2')) {
            define('CURL_SSLVERSION_TLSv1_2', 6);
        }
        $url = 'https://ali.duhuitech.com/v1/convert?url='.$file_url.'&type=xlsx&callbackurl='.getenv('DOC2PDF_CALLBACK');
        $appcode = getenv('DOC2PDF');
        $response = Http::withHeaders([
            'Authorization' => 'APPCODE ' . $appcode,
        ])->withOptions([
            'ssl' => [
                'ciphers' => 'TLSv1.1',
            ],
        ])->get($url);
        $res = json_decode($response, true);
        Log::info('文档转换结果', ['url' => $url,'res' => $res]);
        if ($res['code'] == 10000 && !empty($res['result']['token'])) {
            if ($is_new) {
                \Modules\Basic\Models\DocConvert::create([
                    'file_ori' => $file_url,
                    'table_name' => $table_name,
                    'table_id' => $table_id,
                    'table_col' => $table_col,
                    'token' => $res['result']['token'],
                ]);
                return true;
            }
            if (!$is_new) {
               return $res['result']['token'];
            }

        }
        return false;
    }
}
